package cn.hls.web.task;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hls.entity.Car;
import cn.hls.entity.CertSet;
import cn.hls.entity.Company;
import cn.hls.entity.Member;
import cn.hls.entity.SmsAdvice;
import cn.hls.service.CarService;
import cn.hls.service.CertSetService;
import cn.hls.service.CompanyService;
import cn.hls.service.MemberService;
import cn.hls.service.SmsAdviceService;
import cn.hls.until.GenericsUtils;
import cn.hlsconstant.CommonEnum;

 
 
/**
  *@fileName: JobService.java
  *@package: cn.hls.web.task
　*@Description: 定时任务
　*@author: yinghui.zhang
　*@email: uuhui@163.com
  *@date: 2016年11月6日
 *
 */
@Service("jobService")
public class JobService {
	private Log log = LogFactory.getLog(JobService.class);
	@Resource(name="certSetService")
	private CertSetService certSetService;
	@Resource(name="companyService")
	private CompanyService companySerive;
	@Resource(name="memberService")
	private MemberService memberService;
	@Resource(name="carService")
	private CarService carService;
	@Resource(name="smsAdviceService")
	private SmsAdviceService smsAdviceService;
	/**
	 * 相关证件有效期过期短信提示
	 * @throws Exception
	 */
	
	public void sendMsgOfExpired() throws Exception {
		log.info("----------------证件有效期过期短信发送开始-----------------");
		try {
			Map<String,CertSet>certSetMap=certSetService.loadcertSetInfoToMap(null);
			//获取企业的安管人员列表信息
			Member tempEntity=new Member();
			tempEntity.setType(Integer.valueOf(CommonEnum.SAFETYOFFICER.getCode()));
			List<Member>safeMemberList=memberService.loadMemberList(tempEntity);
			Map<Long,List<Member>>memberMap=memberService.getMemberListToMap(safeMemberList);
			/**企业相关证件有效期过期提示**/
			sendMsgOfCompany(certSetMap,memberMap);
			/**车辆相关证件有效期 过期提示**/
			sendMsgOfCar(certSetMap,memberMap);
			/**人员相关证件有效期过期提示**/
			sendMsgOfMember(certSetMap,memberMap);
		} finally {
			log.info("----------------证件有效期过期短信发送结束-----------------");
		}
	}
	
	/**
	 * 分送企业相关证件有效期过期的提示信息
	 * @param certSetMap 到期提示集合
	 * @param safetMemberMap 安管人员集合
	 * @throws Exception
	 */
	private void sendMsgOfCompany(Map<String, CertSet> certSetMap,
			Map<Long,List<Member>>safetMemberMap)throws Exception {
		List<Company>companyList=companySerive.loadExpiredCompanyList(null,certSetMap);
		for(Company item:companyList){
			sendMsgToCompanyManagers(item,certSetMap,safetMemberMap);
		}
	}

	/**
	 * 发送企业相关证件过期的短信提示信息
	 * @param company 企业信息
	 * @param safetMemberMap 安管人员信息
	 * @param certSetMap
	 */
	private void sendMsgToCompanyManagers(Company company,
			Map<String, CertSet> certSetMap,Map<Long,List<Member>>safetMemberMap)throws Exception{
		Map<String,String> infoMap=getSendMsgOfCompany(company,certSetMap);
		//发送短信给企业法人
		//企业法人及联系电话存在
		if(StringUtils.hasText(company.getLegalMan())&& StringUtils.hasText(company.getLegalManPhone())){
			Iterator<Map.Entry<String, String>>iterator=infoMap.entrySet().iterator();
			while(iterator.hasNext()){
				Map.Entry<String, String >entry=iterator.next();
				String smsContent="企业的"+entry.getValue()+"快过期，请安排工作人员尽快办理";
				Integer dateDiff=certSetMap.get(entry.getKey())==null?1:certSetMap.get(entry.getKey()).getWarnInterval();
				SmsAdvice smsAdvice=new SmsAdvice(Integer.parseInt(CommonEnum.COMPANYSMS.getCode()),company.getId(), entry.getKey(), dateDiff);
				if(!smsAdviceService.exists(smsAdvice)){//不存在,则发送的短信信息
				Integer status=GenericsUtils.sendMsg(new String[]{company.getLegalManPhone()},smsContent);
				//发送短信通知保存
				smsAdviceService.add(new SmsAdvice(Integer.parseInt(CommonEnum.COMPANYSMS.getCode()), company.getId(), entry.getKey(),
						company.getLegalManPhone(),company.getLegalManPhone(),smsContent,status));
				}
			}

		}
		//发送短信给企业安管人员
		List<Member>safeMemberList=safetMemberMap.get(company.getId());
		if(safeMemberList!=null && !safeMemberList.isEmpty()){
			for(Member item:safeMemberList){
				Iterator<Map.Entry<String, String>>iterator=infoMap.entrySet().iterator();
				while(iterator.hasNext()){
					Map.Entry<String, String >entry=iterator.next();
					String smsContent="企业的"+entry.getValue()+"快过期，请尽快办理";
					Integer dateDiff=certSetMap.get(entry.getKey())==null?1:certSetMap.get(entry.getKey()).getWarnInterval();
					SmsAdvice smsAdvice=new SmsAdvice(Integer.parseInt(CommonEnum.COMPANYSMS.getCode()),item.getId(), entry.getKey(), dateDiff);
					if(!smsAdviceService.exists(smsAdvice)){//不存在,则发送的短信信息
					Integer status=GenericsUtils.sendMsg(new String[]{item.getContractPhone()},smsContent);
					//发送短信通知保存
					smsAdviceService.add(new SmsAdvice(Integer.parseInt(CommonEnum.COMPANYSMS.getCode()), item.getId(), entry.getKey(),
							item.getName(),item.getContractPhone(),smsContent,status));
					}
				}
			}
		}
		
	}
	
	//创建车辆相关证件过期的短信
		private Map<String,String> getSendMsgOfCompany(Company company,Map<String, CertSet> certSetMap)throws Exception {
			Map<String,String>map=new HashMap<String, String>();
			if(company.getBussinessRegisteValidity()!=null){//企业执照
				Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("bussinessRegiste")==null?1:certSetMap.get("bussinessRegiste").getPreMonth().intValue());
				if(GenericsUtils.compareTime(company.getBussinessRegisteValidity(), date)<0){
					map.put("bussinessRegiste", "营业执照有效期");
				}
			}else{
				map.put("bussinessRegiste", "营业执照有效期");
			}
			if(company.getBussinessLicenseValidity()!=null){//经营许可证
				Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("bussinessLicense")==null?1:certSetMap.get("bussinessLicense").getPreMonth().intValue());
				if(GenericsUtils.compareTime(company.getBussinessLicenseValidity(), date)<0){
					 map.put("bussinessLicense", "经营许可证有效期");
				}
			}else{
				map.put("bussinessLicense", "经营许可证有效期");
			}
			return map;
		}	
	
	/**
	 * 车辆相关证件有效期过期发送短信提示
	 * @param certSetMap 到期提示集合
	 * @param safeMemberMap 安管人员集合信息
	 * @throws Exception
	 */
	private void sendMsgOfCar(Map<String,CertSet>certSetMap,Map<Long,List<Member>>safeMemberMap)throws Exception{
		List<Car>carList=carService.loadExpiredCarList(null, certSetMap);//相关证件过期的车辆信息
		for(Car item:carList){//遍历车辆遍历发短信发送给相关的管理人员
			sendMsgToCarManagers(item,certSetMap,safeMemberMap);
		}
	}
	
	/**
	 * 发送短信给车辆相关的管理人员
	 * @param car 车辆信息 
	 * @param safeMemberMap 安管人员集合
	 * @param certSetMap 到期提示集合
	 * @throws Exception
	 */
	public void sendMsgToCarManagers(Car car,Map<String,CertSet>certSetMap,Map<Long,List<Member>>safeMemberMap)throws Exception{
		Map<String,String> infoMap=getSendMsgOfCar(car,certSetMap);
		//发送短信给企业法人
		Company company=car.getCompany();
		if(company!=null){
			//企业法人及联系电话存在
			if(StringUtils.hasText(company.getLegalMan())&& StringUtils.hasText(company.getLegalManPhone())){
				Iterator<Map.Entry<String, String>>iterator=infoMap.entrySet().iterator();
				while(iterator.hasNext()){
					Map.Entry<String, String >entry=iterator.next();
					String smsContent="车牌["+car.getLicenseNum()+"相关的]"+entry.getValue()+"快过期，请尽快办理";
					Integer dateDiff=certSetMap.get(entry.getKey())==null?1:certSetMap.get(entry.getKey()).getWarnInterval();
					SmsAdvice smsAdvice=new SmsAdvice(Integer.parseInt(CommonEnum.CARSMS.getCode()),company.getId(), entry.getKey(), dateDiff);
					if(!smsAdviceService.exists(smsAdvice)){//不存在,则发送的短信信息
					Integer status=GenericsUtils.sendMsg(new String[]{company.getLegalManPhone()},smsContent);
					//发送短信通知保存
					smsAdviceService.add(new SmsAdvice(Integer.parseInt(CommonEnum.CARSMS.getCode()), company.getId(), entry.getKey(),
							company.getLegalManPhone(),company.getLegalManPhone(),smsContent,status));
					}
				}
			}
			//发送短信给企业安管人员
			List<Member>safeMemberList=safeMemberMap.get(company.getId());
			if(safeMemberList!=null && !safeMemberList.isEmpty()){
				for(Member item:safeMemberList){
					Iterator<Map.Entry<String, String>>iterator=infoMap.entrySet().iterator();
					while(iterator.hasNext()){
						Map.Entry<String, String >entry=iterator.next();
						String smsContent="车牌为["+car.getLicenseNum()+"相关的]"+entry.getValue()+"快过期，请尽快办理";
						Integer dateDiff=certSetMap.get(entry.getKey())==null?1:certSetMap.get(entry.getKey()).getWarnInterval();
						SmsAdvice smsAdvice=new SmsAdvice(Integer.parseInt(CommonEnum.CARSMS.getCode()),item.getId(), entry.getKey(), dateDiff);
						if(!smsAdviceService.exists(smsAdvice)){//不存在,则发送的短信信息
							Integer status=GenericsUtils.sendMsg(new String[]{company.getLegalManPhone()},smsContent);
							//发送短信通知保存
							smsAdviceService.add(new SmsAdvice(Integer.parseInt(CommonEnum.CARSMS.getCode()), item.getId(), entry.getKey(),
									item.getName(),item.getContractPhone(),smsContent,status));
						}
					}
				}
			}
		}
	}
	//创建车辆相关证件过期的短信
	private Map<String,String> getSendMsgOfCar(Car car,Map<String, CertSet> certSetMap)throws Exception {
		Map<String,String> map=new HashMap<String, String>();
		if(car.getForcedInsuranceTime()!=null){//强制保险过期
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("forcedInsurance")==null?1:certSetMap.get("forcedInsurance").getPreMonth().intValue());
			if(GenericsUtils.compareTime(car.getForcedInsuranceTime(), date)<0){
				map.put("forcedInsurance", "强制保险有效期");
			}
		}
		if(car.getThirdInsuranceTime()!=null){//第三责任险
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("thirdInsurance")==null?1:certSetMap.get("thirdInsurance").getPreMonth().intValue());
			if(GenericsUtils.compareTime(car.getThirdInsuranceTime(), date)<0){
				map.put("thirdInsurance","第三责任险有效期");
			}
		}
		if(car.getCarrierInsuranceTime()!=null){//承运人责任险
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("carrierInsurance")==null?1:certSetMap.get("carrierInsurance").getPreMonth().intValue());
			if(GenericsUtils.compareTime(car.getCarrierInsuranceTime(), date)<0){
				map.put("carrierInsurance","承运人责任险有效期");
			}
		}
		if(car.getDriveExamTime()!=null){//行驶证年审
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("driveExam")==null?1:certSetMap.get("driveExam").getPreMonth().intValue());
			if(GenericsUtils.compareTime(car.getDriveExamTime(), date)<0){
				map.put("driveExam","行驶证年审有效期");
			}
		}
		if(car.getTransLicenseValidityTime()!=null){//道路运输证年审过期
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("transLicenseExam")==null?1:certSetMap.get("transLicenseExam").getPreMonth().intValue());
			if(GenericsUtils.compareTime(car.getTransLicenseValidityTime(), date)<0){
				map.put("transLicenseExam","道路运输证年审有效期");
			}
		}
		if(car.getTankExamTime()!=null){//罐体年检
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("tankExam")==null?1:certSetMap.get("tankExam").getPreMonth().intValue());
			if(GenericsUtils.compareTime(car.getTankExamTime(), date)<0){
				map.put("tankExam","罐体年检有效期");
			}
		}
		if(car.getTechicalGradeTime()!=null){//技术等级评定
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("techicalGrade")==null?1:certSetMap.get("techicalGrade").getPreMonth().intValue());
			if(GenericsUtils.compareTime(car.getTechicalGradeTime(), date)<0){
				map.put("techicalGrade","技术等级评定有效期");
			}
		}
		if(car.getSecondMaintenanceTime()!=null){//二级维护
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("secondMaintenance")==null?1:certSetMap.get("secondMaintenance").getPreMonth().intValue());
			if(GenericsUtils.compareTime(car.getSecondMaintenanceTime(), date)<0){
				map.put("secondMaintenance","二级维护有效期");
			}
		}
		return map;
	}
	/**
	 * 人员相关证件有效期过期提示
	 * @param certSetMap 到期提示集合
	 * @param safeMemberMap 安管人员集合
	 * @throws Exception
	 */
	private void sendMsgOfMember(Map<String,CertSet>certSetMap,Map<Long,List<Member>>safeMemberMap)throws Exception{
		List<Member>memberList=memberService.loadMemberOfExpired();
		for(Member entity:memberList){
			 sendMsgToMember(entity,entity.getCompany(),certSetMap,safeMemberMap);
		}
	}
	/**
	 * @param entity 人员对象信息
	 * @param company 人员所在的企业信息
	 * @param safeMemberMap 安管人员集合
	 * @throws Exception
	 */
	private void sendMsgToMember(Member entity,Company company,Map<String,CertSet>certSetMap,Map<Long,List<Member>>safetMemberMap)throws Exception{
		//发送给证件过期的持证人
		Map<String,String> infoMap= getSendMsgInfoOfMember(entity,certSetMap);//获取发送短信的内容
		if(infoMap!=null&&!infoMap.isEmpty()){
			Iterator<Map.Entry<String, String>>iterator=infoMap.entrySet().iterator();
			while(iterator.hasNext()){
				Map.Entry<String, String >entry=iterator.next();
				String smsContent="您的"+entry.getValue()+"快过期，请尽快办理。";
				Integer dateDiff=certSetMap.get(entry.getKey())==null?1:certSetMap.get(entry.getKey()).getWarnInterval();
				SmsAdvice smsAdvice=new SmsAdvice(Integer.parseInt(CommonEnum.MEMBERSMS.getCode()),entity.getId(), entry.getKey(), dateDiff);
				if(!smsAdviceService.exists(smsAdvice)){//不存在,则发送的短信信息
					Integer status=GenericsUtils.sendMsg(new String[]{entity.getContractPhone()},smsContent);
					//发送短信通知保存
					smsAdviceService.add(new SmsAdvice(Integer.parseInt(CommonEnum.MEMBERSMS.getCode()), entity.getId(), entry.getKey(),
							entity.getName(),entity.getContractPhone(),smsContent,status));
				}
			}
		}
		//发送企业法人
		if(StringUtils.hasText(company.getLegalMan())&& StringUtils.hasText(company.getLegalManPhone())){
			Iterator<Map.Entry<String, String>>iterator=infoMap.entrySet().iterator();
			while(iterator.hasNext()){
				Map.Entry<String, String >entry=iterator.next();
				String smsContent="员工["+entity.getName()+"的]"+entry.getValue()+"快过期，请尽快办理";
				Integer dateDiff=certSetMap.get(entry.getKey())==null?1:certSetMap.get(entry.getKey()).getWarnInterval();
				SmsAdvice smsAdvice=new SmsAdvice(Integer.parseInt(CommonEnum.MEMBERSMS.getCode()),company.getId(), entry.getKey(), dateDiff);
				if(!smsAdviceService.exists(smsAdvice)){//不存在,则发送的短信信息
				Integer status=GenericsUtils.sendMsg(new String[]{company.getLegalManPhone()},smsContent);
				//发送短信通知保存
				smsAdviceService.add(new SmsAdvice(Integer.parseInt(CommonEnum.MEMBERSMS.getCode()), company.getId(), entry.getKey(),
						company.getLegalManPhone(),company.getLegalManPhone(),smsContent,status));
				}
			}
		}
		//发送信息给安管人员
		if(company!=null){
			List<Member>safetMemberList=safetMemberMap.get(company.getId());
			if(safetMemberList!=null &&!safetMemberList.isEmpty()){
				for(Member item:safetMemberList){
					if(StringUtils.hasText(item.getContractPhone())){
						Iterator<Map.Entry<String, String>>iterator=infoMap.entrySet().iterator();
						while(iterator.hasNext()){
							Map.Entry<String, String >entry=iterator.next();
							String smsContent="员工["+entity.getName()+"的]"+entry.getValue()+"快过期，请尽快办理。";
							Integer dateDiff=certSetMap.get(entry.getKey())==null?1:certSetMap.get(entry.getKey()).getWarnInterval();
							SmsAdvice smsAdvice=new SmsAdvice(Integer.parseInt(CommonEnum.MEMBERSMS.getCode()),item.getId(), entry.getKey(), dateDiff);
							if(!smsAdviceService.exists(smsAdvice)){//不存在,则发送的短信信息
								Integer status=GenericsUtils.sendMsg(new String[]{company.getLegalManPhone()},smsContent);
								//发送短信通知保存
								smsAdviceService.add(new SmsAdvice(Integer.parseInt(CommonEnum.MEMBERSMS.getCode()), company.getId(), entry.getKey(),
										item.getName(),item.getContractPhone(),smsContent,status));
							}
						}
					}
				}
			}
		}
		
	}
	
	private Map<String,String> getSendMsgInfoOfMember(Member entity,Map<String,CertSet>certSetMap)throws Exception	{
		Map<String,String> map=new HashMap<String, String>();
		if(entity.getDriverLiceseNum()!=null){//存在驾驶证的过期信息
			//设置比较时间
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("driverLiceseNum")==null?1:certSetMap.get("driverLiceseNum").getPreMonth().intValue());
			if(entity.getDriverLiceseNumValidity()==null||GenericsUtils.compareTime(entity.getDriverLiceseNumValidity(), date)<=0){
				map.put("driverLiceseNum","驾驶证有效期");
			}
		}
		if(entity.getDriverQuaCertNum()!=null){//存在驾驶资格证的过期信息
			//设置比较时间
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("driverQuaCertNum")==null?1:certSetMap.get("driverQuaCertNum").getPreMonth().intValue());;
			if(entity.getDriverQuaCertNumValidity()==null||GenericsUtils.compareTime(entity.getDriverQuaCertNumValidity(), date)<=0){
				map.put("driverQuaCertNum","驾驶资格证有效期");
			}
		}
		if(entity.getSuperCargoNum()!=null){//押运员从业资格证的过期信息
			//设置比较时间
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("superCargoNum")==null?1:certSetMap.get("superCargoNum").getPreMonth().intValue());;
			if(entity.getSuperCargoNumValidity()==null||GenericsUtils.compareTime(entity.getSuperCargoNumValidity(), date)<=0){
				map.put("superCargoNum","押运员从业资格证有效期");
			}
		}
		if(entity.getSafetyOfficerNum()!=null){//安管员从业资格证资格证的过期信息
			//设置比较时间
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("safetyOfficerNum")==null?1:certSetMap.get("safetyOfficerNum").getPreMonth().intValue());;
			if(entity.getSafetyOfficerNumValidity()==null||GenericsUtils.compareTime(entity.getSafetyOfficerNumValidity(), date)<=0){
				map.put("safetyOfficerNum","安管员从业资资格证有效期");
			}
		}
		
		if(entity.getMainPersonResNum()!=null){//主要负责人从业资格证的过期信息
			//设置比较时间
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("mainPersonResNum")==null?1:certSetMap.get("mainPersonResNum").getPreMonth().intValue());;
			if(entity.getMainPersonResNumValidity()==null||GenericsUtils.compareTime(entity.getMainPersonResNumValidity(), date)<=0){
				map.put("mainPersonResNum","主要负责人从业资格证有效期");
			}
		}
		if(entity.getLoadUnloadManNum()!=null){//装卸管理员从业资格证的过期信息
			//设置比较时间
			Date date=GenericsUtils.getPreMonthTime(new Date(),certSetMap.get("loadUnloadManNum")==null?1:certSetMap.get("loadUnloadManNum").getPreMonth().intValue());;
			if(entity.getLoadUnloadManNumValidity()==null||GenericsUtils.compareTime(entity.getLoadUnloadManNumValidity(), date)<=0){
				map.put("loadUnloadManNum","装卸管理员从业资格证有效期");
			}
		}
	    return map;
	}
}
